package KK.System.Pool
{
	import KK.KKQueue.IKKQueue;
	import KK.KKQueue.KKQueue;
	
	import flash.utils.getTimer;

	public class PoolManager implements IPoolManager
	{
		static private const UN_FIND:int=-1;//未找到对象
		private var poolList:Vector.<IPool>;
//		private var UnUsedList:Vector.<IPool>;
		private var UnUsedQueue:IKKQueue;
		
		private var buffCount:uint;//缓冲数量
		private var PoolClass:Class;
		public function PoolManager(PoolClass:Class)
		{
			//TODO: implement function
			this.PoolClass=PoolClass;
			init();
		}
		private function init():void{
			BuffSize=2;
			poolList=new Vector.<IPool>;
//			UnUsedList=new Vector.<IPool>;
			UnUsedQueue=new KKQueue;
		}
		
		/**
		 * 获取对象  
		 * @return 
		 * 
		 */
		public function Creater():IPool
		{
			//TODO: implement function
			var result:IPool;
			result=UnUsedPool;
			if(null==result){
				var i:int=0;
				while(i<BuffSize){
					result=CreatePool();
					if(result){
						poolList.push(result);
						result.UnUsed();
					}
					i++;
				}
				
				result=UnUsedPool;
			}
			if(result){
				result.Using();
			}
			return result;
		}
		
		/**
		 * 创建新Pool 
		 * @return 
		 * 
		 */
		protected function CreatePool():IPool{
			var result:IPool=new PoolClass;
			
			return result;
		}
		/**
		 * 添加一个
		 * @param pool
		 * 
		 */
		public function AddPool(pool:IPool):void{
			poolList.push(pool)
			pool.Using();
		}
		
		/**
		 * 移除对象  
		 * @param pool
		 * 
		 */
		public function Remove(pool:IPool):void
		{
			//TODO: implement function
			pool.UnUsed();
		}
		
		
		
		/**
		 *  查找对象位置 
		 * @return 
		 * 
		 */
		private function FindPoolPosition(pool:IPool):int{
			var result:int;
			const nlen:int=poolList.length;
			var i:int=0;
			while(i<nlen){
				
				if(pool==poolList[i])
				{
					result=i;
					break;
				}
				i++;
			}
			
			return result;
		}
		
		
		/**
		 * 查找一个未使用的对象 
		 * @return 
		 * 
		 */
		private function FindUnUsed():IPool{ 
			var result:IPool;
			var i:int=0;
			result=IPool(UnUsedQueue.PeekQueue());
			if(!result){
				const nLen:int=poolList.length;
				while(i<nLen){
					if(poolList[i].PoolStatus==Pool.UNUSED){
//						UnUsedList.push(poolList[i]);
						UnUsedQueue.AddQueue(poolList[i]);
					}
					i++;
				}
			}
			if(!result)
			{
				result=IPool(UnUsedQueue.PeekQueue());
			}
			return result;
		}
		
		/**
		 * 获取一个未使用Pool 
		 * @return 
		 * 
		 */
		private function get UnUsedPool():IPool{
			var result:IPool=FindUnUsed();
			
			return result;
		}
		
		
		/**
		 * 设置缓冲数量 
		 * @param value
		 * 
		 */
		public function set BuffSize(value:uint):void{
			if(value<1){
				value=1;
			}
			this.buffCount=value;
		}
		/**
		 * 获取缓冲数量 
		 * @return 
		 * 
		 */
		public function get BuffSize():uint{
			return this.buffCount;
		}
	}
}